package com.huwaiwai.zookeeper.demo02;

import com.google.common.collect.Lists;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
import java.util.Random;

/**
 * Created by huweiwei on 2017/4/7.
 */
public class SimpleClient {
    public static void main(String [] args){
        initServerList();
        SimpleClient client = new SimpleClient();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String name;
            try {
                name = reader.readLine();
                if ("exit".equals(name)) {
                    System.exit(0);
                }
                client.send(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private static List<String> servers = Lists.newArrayList();
    private static void initServerList() {
        String path = "/test";
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 60000, 1000);
        List<String> clilds = zkClient.getChildren(path);
        servers.clear();
        clilds.forEach(clild -> servers.add(clild));
        zkClient.subscribeChildChanges("/test", new IZkChildListener() {
            @Override
            public void handleChildChange(String s, List<String> list) throws Exception {
                System.out.println(String.format("[ZookeeperRegistry] service list change: path=%s, currentChilds=%s", s, list.toString()));
                servers.clear();
                list.forEach(i -> servers.add(zkClient.readData(path + "/" + i)));
                System.out.println("servers: " + servers.toString());
            }
        });
    }

    static String getServer() {
        return servers.get(new Random().nextInt(servers.size()));
    }

    public void send(String name) {
        String server = SimpleClient.getServer();
        String[] cfg = server.split(":");
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket(cfg[0], Integer.parseInt(cfg[1]));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println(name + Integer.parseInt(cfg[1]));
            while(true) {
                String resp = in.readLine();
                if(resp == null)
                    break;
                else if(resp.length() > 0) {
                    System.out.println("Receive : " + resp);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
